import React from 'react'
import { createRoot } from 'react-dom/client'
import { Button, Card, Space, Typography } from 'antd'
import 'antd/dist/reset.css'

const { Title, Text } = Typography

class AntdWebComponent extends HTMLElement {
  private root: any = null

  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
  }

  connectedCallback() {
    this.render()
  }

  disconnectedCallback() {
    if (this.root) {
      this.root.unmount()
      this.root = null
    }
  }

  render() {
    // 获取属性
    const title = this.getAttribute('title') || 'Ant Design Web Component'
    const description = this.getAttribute('description') || '这是一个使用 Ant Design 的 Web Component'

    // 创建 shadow DOM 结构
    this.shadowRoot!.innerHTML = `
      <div id="react-container" style="display: inline-block;"></div>
      <slot></slot>
    `

    // 在 shadow DOM 中渲染 React 组件
    const container = this.shadowRoot!.getElementById('react-container')
    if (container) {
      this.root = createRoot(container)
      this.root.render(
        React.createElement(
          Card,
          {
            style: { width: 300, margin: '16px' },
            bordered: true
          },
          React.createElement(Title, { level: 4 }, title),
          React.createElement(Text, null, description),
          React.createElement('div', { style: { marginTop: '16px' } },
            React.createElement(Space, null,
              React.createElement(Button, { type: 'primary' }, '主要按钮'),
              React.createElement(Button, null, '默认按钮')
            )
          )
        )
      )
    }
  }
}

// 定义 Web Component
if (!customElements.get('antd-web-component')) {
  customElements.define('antd-web-component', AntdWebComponent)
}

// 导出 React 组件包装器
export const AntdWebComponentWrapper = (props: { 
  title?: string; 
  description?: string; 
  children?: React.ReactNode 
}) => {
  return React.createElement('antd-web-component', {
    title: props.title,
    description: props.description
  }, props.children)
}

export { AntdWebComponent }